//
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');

var async = require('async');
var express = require('express');
var fs = require("fs");
var crypto = require('crypto');

//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
//  * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);

router.set('views', path.join(__dirname, 'views'));
router.set('view engine', 'ejs');
router.use(express.static(path.resolve(__dirname, 'static')));
router.use(express.bodyParser());


var text = fs.readFileSync("word_movie_info", 'utf8');
var all_word_infos = JSON.parse(text);


router.get("/", function(req, res) {
  res.render("index.ejs",  {
    all_word_infos: all_word_infos
  });
});

router.get("/word", function(req, res) {
  var word = req.query.word;

  if (req.query.next) {
    var info;
    for (var i = 0; i < all_word_infos.length; i ++) {
      var aInfo = all_word_infos[i];
      if (req.query.next == aInfo.word) {
        info = all_word_infos[i + 1 < all_word_infos.length ? i + 1 : all_word_infos.length].info
        word = all_word_infos[i + 1 < all_word_infos.length ? i + 1 : all_word_infos.length].word
        break;
      }
    }

    res.render("word.ejs", {
      subs: info,
      word: word
    });

    return;
  }

  if (!word) {
    word = all_word_infos[0].word
  }

  var info;
  for (var i = 0; i < all_word_infos.length; i ++) {
    var aInfo = all_word_infos[i];
    if (word == aInfo.word) {
      info = aInfo.info
      break;
    }
  }

  res.render("word.ejs", {
    subs: info,
    word: word
  });
});

router.get("/movie", function(req, res) {
  var movie = req.query.movie;
  var start = req.query.start;
  var end = req.query.end;
  var text = req.query.text;
  var word = req.query.word;

  if (!movie || !start || movie.indexOf(".") === -1 || !end || !word || !text) {
    res.send("Invalid request");
    return;
  }

  start = start.replace(",", ".");
  var slices = start.split(":");
  var startSeconds = 0;
  var coefficient = 3600;

  if (slices.length === 3) {
    for (var i = 0; i < slices.length; i ++) {
      startSeconds += parseFloat(slices[i], 10) * coefficient;
      coefficient = coefficient / 60;
    }
  }

  end = end.replace(",", ".");
  var slices = end.split(":");
  var stopSeconds = 0;
  var coefficient = 3600;

  if (slices.length === 3) {
    for (var i = 0; i < slices.length; i ++) {
      stopSeconds += parseFloat(slices[i], 10) * coefficient;
      coefficient = coefficient / 60;
    }
  }



  fs.readdir("./static/all_movie/", (err, files) => {
    files.forEach(file => {
      if (file.slice(0, file.indexOf(".")).toLowerCase() === movie.slice(0, movie.indexOf(".")).toLowerCase()) {
        movieUrl = "./all_movie/" + file

        res.render("movie.ejs", {
          movieUrl: movieUrl,
          seconds: startSeconds,
          end: stopSeconds,
          text : text,
          word: word,
          contentId : crypto.createHash('md5').update(text).digest('hex')
        });
      }
    });
  });
});

router.post("/confirm", function(req, res) {
  delete req.body.__proto__

  fs.readFile('the_choosen_one.txt', 'utf8', function(err, content) {
    if (err) {
      content = "";
    }

    var isFound = false;
    var lines = content.split("\n");

    for (var i = lines.length - 1; i >= 0; i --) {
      var line = lines[i];
      if (line.trim()) {
        var content = JSON.parse(line);
        if (content.contentId === req.body.contentId) {
          if (!isFound) {
            lines[i] = JSON.stringify(req.body);
          } else {
            delete lines[i];
          }
            isFound = true;
        }
      } else {
          console.log("aaaaa");
          delete lines.splice(i, 1);
      }
    }

    content = lines.join("\n");

    if (!isFound) {
      content = content + "\n" + JSON.stringify(req.body) + "\n";
    }

    fs.writeFile('the_choosen_one.txt', content, function(err) {
      res.send("success");
    });

  });
})




server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
  var addr = server.address();
  console.log("server listening at", addr.address + ":" + addr.port);
});
